import { createApp, ref, onMounted, watch } from "https://unpkg.com/vue@3/dist/vue.esm-browser.js";
import { ElMessage } from "https://unpkg.com/element-plus";
import { Fold, Expand, House, User } from "https://unpkg.com/@element-plus/icons-vue";
import router from "/static/js/router.js";
import { checkLoginData } from "/static/js/auth.js";

const app = createApp({
    setup() {
        const isCollapsed = ref(false);
        const username = ref("Admin");
        const activeMenu = ref("/home");

        const toggleSidebar = () => {
            isCollapsed.value = !isCollapsed.value;
        };

        const handleMenuSelect = (index) => {
            activeMenu.value = index;
            router.push(index);
        };

        const goToProfile = () => {
            ElMessage.info("进入个人中心");
        };

        const logout = () => {
            localStorage.removeItem("username");
            localStorage.removeItem("password");
            localStorage.removeItem("expires");
            ElMessage.success("已退出登录");
            window.location.href = "/index.html";
        };

        onMounted(() => {
            const loginData = checkLoginData();
            if (loginData && loginData.username !== "") {
                ElMessage.success("欢迎 " + loginData.username);

                // 获取 URL Hash，确保刷新后选中正确的菜单
                let currentPath = window.location.hash.replace("#", "") || "/home";
                activeMenu.value = currentPath;
                router.push(currentPath);
            }
        });

        watch(() => router.currentRoute.value.path, (newPath) => {
            activeMenu.value = newPath;
        });

        return {
            isCollapsed,
            username,
            activeMenu,
            toggleSidebar,
            handleMenuSelect,
            goToProfile,
            logout,
            Fold, Expand, House, User
        };
    }
});

app.use(router);
app.use(ElementPlus);
app.mount("#app");
